#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <assert.h>
#include <mutex>
#include <fstream>
#include <jsoncpp/json/json.h>
#include <algorithm>
#include "../comm/httplib.h"
#include "oj_view.hpp"
#include "../comm/log.hpp"
#include "../comm/util.hpp"
// #include "oj_model.hpp"
#include "oj_model2.hpp"
namespace NS_control
{
    using namespace httplib;
    using namespace std;
    using namespace NS_log;
    using namespace NS_util;
    using namespace NS_model;
    using namespace NS_view;

    // 提供服务主机
    class Machine
    {
    public:
        std::string ip;  // 编译服务ip
        int port;        // 编译服务端口
        uint64_t load;   // 编译服务的负载
        std::mutex *mtx; // mutex禁止拷贝，使用指针完成
    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine()
        {
        }

    public:
        void IncLoad() // 提升主机负载
        {
            if (mtx)
                mtx->lock();
            load++;
            if (mtx)
                mtx->unlock();
        }
        void DecLoad() // 减少主机负载
        {
            if (mtx)
                mtx->lock();
            load--;
            if (mtx)
                mtx->unlock();
        }
        void ResetLoad()
        {
            if(mtx) mtx->lock();
            load = 0;
            if(mtx) mtx->unlock();
        }
        // 获取主机负载
        uint64_t Load()
        {
            uint64_t _load = 0;
            if (mtx)
                mtx->lock();
            load = _load;
            if (mtx)
                mtx->unlock();
            return _load;
        }
    };

    const std::string service_machine = "./conf/service_machine.conf";


    // 负载均衡模块，初始化主机信息
    class LoadBlance
    {
    private:
        std::vector<Machine> _machines; // 可以提供编译服务的所有主机，下标充当id
        std::vector<int> _online;       // 所有在线主机id
        std::vector<int> _offline;      // 所有离线主机id
        std::mutex mtx; //给主机传锁

    public:
        LoadBlance()
        {
            assert(LoadConf(service_machine));
            LOG(INFO) << "加载" << service_machine << "成功" << "\n";
        }
        ~LoadBlance()
        {
        }

    public:
        bool LoadConf(const std::string &machine_conf)
        {
            std::ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载：" << machine_conf << "失败" << "\n";
                return false;
            }
            std::string line;
            while (std::getline(in, line))
            {
                std::vector<std::string> tokens;
                Stringutil::SpiltString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "切分" << line << "失败" << "\n";
                    continue;
                }
                Machine m;
                m.ip = tokens[0];
                m.port = std::stoi(tokens[1]);
                m.mtx = new std::mutex();//这里在给每个主机new了mutex
                _online.push_back(_machines.size());
                _machines.push_back(m);
            }
            in.close();
            return true;
        }

        bool SmartChoice(int *id, Machine **m)
        {
            // 使用选择好的主机
            // 我们需要离线该主机
            mtx.lock();
            // 负载均衡的算法
            // 轮询选择
            int online_num = _online.size();
            if (online_num == 0)
            {
                LOG(FATAL) << "所有后端主机已经离线" << "\n";
                mtx.unlock();
                return false;
            }
            // 通过遍历，找到负载最小的机器
            *id = _online[0];
            *m = &_machines[_online[0]];
            uint64_t min_load = _machines[_online[0]].Load();
            for (int i = 1; i < online_num; i++)
            {
                uint64_t curr_load = _machines[_online[i]].Load();
                if (min_load > curr_load)
                {
                    min_load = curr_load;
                    *id = _online[i];
                    *m = &_machines[_online[i]];
                }
            }
            mtx.unlock();
            return true;
        }

        void OfflineMachine(int which)
        {
            mtx.lock();
            for (auto iter = _online.begin(); iter != _online.end(); iter++)
            {
                if (*iter == which)
                {
                    _machines[which].ResetLoad();
                    _online.erase(iter);//迭代器失效，不要解引用
                    _offline.push_back(which);
                    break; // 不考虑迭代器失效问题
                }
            }
            mtx.unlock();
            LOG(INFO) << "所有主机又上线了" << "\n";
        }

        void OnlineMachine()
        {
            mtx.lock();
            _online.insert(_online.end(),_offline.begin(),_offline.end());
            _offline.erase(_offline.begin(),_offline.end());
            mtx.unlock();
        }

        void ShowMachine()
        {
            mtx.lock();
            std::cout << "当前在线主机列表： ";
            for (auto &id : _online)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            std::cout << "当前离线主机列表： ";
            for (auto &id : _offline)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            mtx.unlock();
        }
    };

    // 核心业务逻辑控制器
    class Control
    {
    private:
        Model _model;            // 后台数据
        View _view;              // 提供html渲染功能
        LoadBlance _load_blance; // 核心负载均衡器
    public:
        Control()
        {
        }
        ~Control()
        {
        }
        void RecoverMachine()
        {
            _load_blance.OnlineMachine();
        }
        // 根据题目数据构建html网页
        bool AllQuestions(string *html)
        {
            bool ret = true;
            vector<Question> all;
            if (_model.GetAllQuestions(&all))
            {
                sort(all.begin(),all.end(),[](const Question &q1,const Question &q2){
                    return std::stoi(q1.number) < std::stoi(q2.number);
                });
                // 获取题目信息成功，将所有的题目数据构建为网页
                _view.AllExpandHtml(all, html);
            }
            else
            {
                *html = "获取题目失败，形成题目列表失败";
                ret = false;
                return false;
            }
            return true;
        }

        bool question(const string &number, string *html)
        {
            bool ret = true;
            Question q;
            if (_model.GetOneQuestion(number, &q))
            {
                // 指定题目信息成功，将所有题目构建为网页
                _view.OneExpandHtml(q, html);
            }
            else
            {
                *html = "指定题目不存在" + number + " 不存在 ";
                ret = false;
                return false;
            }
            return ret;
        }
        // id:
        // code:
        // input:
        void Judge(const std::string &number, const std::string in_json, std::string *out_json)
        {
            //LOG(DEBUG) << in_json << "\nnumber:" << number << std::endl;
            // 0.根据题目获得题目编号，拿到对应的题目细节
            Question q;
            _model.GetOneQuestion(number, &q);
            // 1.in_json进行反序列化，得到题目的id，得到用户提交源代码
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();
            // 2.重新拼接用户代码+测试代码，形成新的一份
            Json::Value complie_value;
            complie_value["input"] = in_value["input"].asString();
            complie_value["code"] = code + '\n' + q.tail;
            complie_value["cpu_limit"] = q.cpu_limit;
            complie_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(complie_value);
            // 3.选择负载最低的主机，发起http请求
            // 规则：一直选择，直到主机可用，否则，全部挂掉
            while (true)
            {
                int id;
                Machine *m = nullptr;
                if (!_load_blance.SmartChoice(&id, &m))
                {
                    break;
                }
                // 发起请求
                Client cli(m->ip, m->port);
                m->IncLoad();
                LOG(INFO) << "选择成功,主机id: " << id << " 详情：" << m->ip << ":" << m->port << "当前主机的负载 " << m->Load() << "\n";
                if (auto res = cli.Post("/compile_and_run", compile_string, "qpplication/json;charset=utf-8"))
                {
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->DecLoad();
                        LOG(INFO) << "请求编译和运行成功..." << "\n"; 
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << "当前请求主机id: " << id << "详情：" << m->ip << ":" << m->port << "可能已经离线了" << "\n";
                    m->DecLoad();
                    _load_blance.OfflineMachine(id);
                    _load_blance.ShowMachine();
                }
            }
            // 4.将结果赋值给out_json
        }
    };
}